package com.ruoyi.base.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.base.domain.BaseClass;
import com.ruoyi.base.domain.BaseRoom;
import com.ruoyi.base.domain.BaseSpecialty;
import com.ruoyi.base.domain.BaseStudent;
import com.ruoyi.base.mapper.BaseClassMapper;
import com.ruoyi.base.mapper.BaseRoomMapper;
import com.ruoyi.base.mapper.BaseSpecialtyMapper;
import com.ruoyi.base.mapper.BaseStudentMapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ValidationUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.base.service.IBaseStudentService;

/**
 * 学生Service业务层处理
 * 
 * @author yepanpan
 * @date 2020-11-09
 */
@Service
public class BaseStudentServiceImpl implements IBaseStudentService 
{
	private static final Logger log = LoggerFactory.getLogger(BaseTeacherServiceImpl.class);
	
    @Autowired
    private BaseStudentMapper baseStudentMapper;
    @Autowired
    private BaseClassMapper baseClassMapper;
    @Autowired
    private BaseRoomMapper baseRoomMapper;
    @Autowired
    private BaseSpecialtyMapper baseSpecialtyMapper;
    
	@Autowired
	private ISysUserService sysUserService;

	@Autowired
	private ISysConfigService configService;
		

    /**
     * 查询自己的学生信息
     * 
     * @return 学生
     */
    public BaseStudent getMyStudent() {
    	BaseStudent bs = new BaseStudent();
    	bs.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
    	BaseStudent vo = baseStudentMapper.findBaseStudent(bs);
    	if(vo == null) {
    		throw new CustomException("没有您的学籍信息");
    	}
    	return vo;
    }

    /**
     * 查询自己的学生信息
     * 
     * @return 学生
     */
    public BaseStudent selectBaseStudentById(Long id) {
    	return baseStudentMapper.selectBaseStudentById(id);
    }

    @Override
    public BaseStudent findStudentByUser(Long userId) {
    	BaseStudent bs = new BaseStudent();
    	bs.setUserId(userId);
    	return baseStudentMapper.findBaseStudent(bs);
    }
    

    /**
     * 生成学号
     * @return String
     */
    @Override
    public String genCode() {
    	String year = DateUtils.dateTimeNow(DateUtils.YYYY);
    	String code = baseStudentMapper.findMaxCode(year);
    	if(code == null || "".equals(code)) {
    		code = year + "0001";
    	}else {
    		code = year + String.format("04d", Integer.parseInt(code.substring(4))+1);
    	}
    	return code;
    }

    /**
     * 查询学生列表
     * 
     * @param StudentVo 学生
     * @return 学生
     */
    @Override
    public List<BaseStudent> selectBaseStudentList(BaseStudent student)
    {
    	List<BaseStudent> list = baseStudentMapper.selectBaseStudentList(student);
    	for(BaseStudent vo:list) {
    		if(vo.getIdcard() ==null || vo.getIdcard().length() < 18) continue;
    		
    		vo.setIdcard(vo.getIdcard().substring(0,8)+"******"+vo.getIdcard().substring(14));
    	}
    	return list;
    }

    /**
     * 新增学生
     * 
     * @param StudentVo 学生
     * @return 结果
     */
    @Override
    @Transactional
    public int insertStudent(BaseStudent student)
    {
    	//判断宿舍
    	if("Y".equalsIgnoreCase(student.getIsLodge())) {
    		if(student.getRoomId() == null || student.getRoomId().intValue() == 0) {
    			throw new CustomException("住校生必须安排宿舍");
    		}
    		BaseStudent bsc = new BaseStudent();
    		bsc.setRoomId(student.getRoomId());
    		bsc.setStatus("1");
    		List<BaseStudent> list = baseStudentMapper.selectBaseStudentList(bsc);
    		BaseRoom room = baseRoomMapper.selectBaseRoomById(student.getRoomId());
    		if(list.size() >= room.getVolume().intValue()) {
    			throw new CustomException("宿舍 "+room.getTitle()+" 已经安排满员");
    		}
    	}else {
    		student.setRoomId(0l);
    	}
    	//同步用户信息
		long userId = saveOrUpdateUser(student, SecurityUtils.getUsername());
		student.setUserId(userId);
		
    	BaseStudent bs = new BaseStudent();
    	BeanUtils.copyProperties(student, bs);
        int stuId = baseStudentMapper.insertBaseStudent(bs);
        student.setId(bs.getId());
    	 
        return stuId;
    }

    /**
     * 修改学生
     * 
     * @param StudentVo 学生
     * @return 结果
     */
    @Override
    @Transactional
    public int updateStudent(BaseStudent student)
    {
    	//判断宿舍
    	if("Y".equalsIgnoreCase(student.getIsLodge())) {    		
    		if(student.getRoomId() == null || student.getRoomId().intValue() == 0) {
    			throw new CustomException("住校生必须安排宿舍");
    		}
    		
    		BaseStudent old = baseStudentMapper.selectBaseStudentById(student.getId());
    		if(!student.getRoomId().equals(old.getRoomId())) {//有换宿舍
        		BaseStudent bsc = new BaseStudent();
        		bsc.setRoomId(student.getRoomId());
        		bsc.setStatus("1");
        		List<BaseStudent> list = baseStudentMapper.selectBaseStudentList(bsc);
        		BaseRoom room = baseRoomMapper.selectBaseRoomById(student.getRoomId());
        		if(list.size() >= room.getVolume().intValue()) {
        			throw new CustomException("宿舍 "+room.getTitle()+" 已经安排满员");
        		}    			
    		}
    	}else {
    		student.setRoomId(0l);
    	}
    	//更新用户信息
    	saveOrUpdateUser(student, SecurityUtils.getUsername());
    	
    	BaseStudent bs = new BaseStudent();
    	BeanUtils.copyProperties(student, bs);    	
    	
    	return baseStudentMapper.updateBaseStudent(bs);
    	        
    }

    /**
     * 批量删除学生
     * 
     * @param ids 需要删除的学生ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteStudentByIds(Long[] ids)
    {
    	for(Long stuId:ids) {
        	BaseStudent bs = baseStudentMapper.selectBaseStudentById(stuId);
			if(bs != null) {
				sysUserService.deleteUserById(bs.getUserId());
			}
		}
        return baseStudentMapper.deleteBaseStudentByIds(ids);
    }

    /**
     * 删除学生信息
     * 
     * @param id 学生ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteStudentById(Long id)
    {
    	BaseStudent bs = baseStudentMapper.selectBaseStudentById(id);
    	if(bs == null) return 0;
    	
    	sysUserService.deleteUserById(bs.getUserId());
        return baseStudentMapper.deleteBaseStudentById(id);
    }
    
    @Override
    @Transactional
	public int updateStudentStatus(Long[] ids, String status) {
    	for(Long userId:ids) {
    		SysUser u = new SysUser();
    		u.setUserId(userId);
    		u.setStatus("1".equals(status) ? "0" : "1");
        	sysUserService.updateUserStatus(u);
    	}
		return baseStudentMapper.updateStudentStatus(ids, status);
	}

	@Override
    @Transactional
	public String importStudent(List<BaseStudent> studentList, Boolean isUpdateSupport, String operName) {

		if (StringUtils.isNull(studentList) || studentList.size() == 0) {
			throw new CustomException("导入数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
       
		for (BaseStudent vo : studentList) {
			List<String> vs = ValidationUtils.validate(vo);
			if (vs != null) {
				failureNum++;
				failureMsg.append(
						"<br/>" + failureNum + "、学生 " + vo.getName() + " 数据不完整：" + CollectionUtils.join(vs, ","));
				continue;
			}
			try {
				 // 验证部门是否存在
            	BaseClass dd = baseClassMapper.findClassByName(vo.getClassName());
            	if(dd == null) {
            		throw new CustomException("班级不"+vo.getClassName()+"存在");
            	}
            	vo.setClassId(dd.getId());
            	vo.setSpecId(dd.getSpecId());
            	
            	if(StringUtils.isNoneBlank(vo.getRoomName())) {
                	BaseRoom brc = new BaseRoom();
                	brc.setTitle(vo.getRoomName());
                	brc.setType("3");
                	brc.setStatus("1");
                	BaseRoom room = baseRoomMapper.findBaseRoom(brc);
                	vo.setRoomId(room.getId());
            	}
				
				// 查找旧数据
            	BaseStudent cond = new BaseStudent();
				cond.setCode(vo.getCode());
				BaseStudent old = baseStudentMapper.findBaseStudent(cond);
				if (StringUtils.isNull(old)) {					
					this.insertStudent(vo);
					successNum++;
					successMsg.append("<br/>" + successNum + "、学生 " + vo.getName() + " 导入成功");
				} else if (isUpdateSupport) {
					vo.setId(old.getId());
					this.updateStudent(vo);
					successNum++;
					successMsg.append("<br/>" + successNum + "、学生 " + vo.getName() + " 更新成功");
				} else {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、学生 " + vo.getName() + " 已存在");
				}
				
			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、学生 " + vo.getName() + " 导入失败：";
				failureMsg.append(msg + e.getMessage());
				log.error(msg, e);
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new CustomException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();

	}
	
	private long saveOrUpdateUser(BaseStudent student, String operName) {
        
		BaseSpecialty bs = baseSpecialtyMapper.selectBaseSpecialtyById(student.getSpecId());
		SysUser user = null;
		if(student.getUserId() != null) {
			user = sysUserService.selectUserById(student.getUserId());
			user.setEmail(student.getEmail());
			user.setNickName(student.getName());
			user.setPhonenumber(student.getMobile());
			user.setSex(student.getSex());	
			user.setDeptId(bs.getDeptId());
			sysUserService.updateUser(user);
			return user.getUserId();
		}
		
		user = sysUserService.selectUserByUserName(student.getCode());
		if(user != null) {
			user.setCreateTime(DateUtils.getNowDate());
			user.setDeptId(-1l);
			user.setEmail(student.getEmail());
			user.setNickName(student.getName());
			user.setPhonenumber(student.getMobile());
			user.setSex(student.getSex());
			user.setDeptId(bs.getDeptId());
			
			sysUserService.updateUser(user);
		}else {

	        String password = configService.selectConfigByKey("sys.user.initPassword");
	        String roles[] = configService.selectConfigByKey("base.role.student").split(",");
	        Long[] role = new Long[roles.length];
	        for(int i=0;i<roles.length;i++) {
	        	role[i] = Long.parseLong(roles[i]);
	        }
	        Long[] post = {4l};
			user = new SysUser();
			user.setCreateBy(operName);
			user.setCreateTime(DateUtils.getNowDate());
			user.setDelFlag("0");
			user.setDeptId(bs.getDeptId());
			user.setEmail(student.getEmail());
			user.setNickName(student.getName());
			user.setUserName(student.getCode());
			user.setPhonenumber(student.getMobile());
			user.setSex(student.getSex());
			user.setStatus("0");
            user.setPassword(SecurityUtils.encryptPassword(password));
            user.setRoleIds(role);
            user.setPostIds(post);
            
            sysUserService.insertUser(user);
		}
		return user.getUserId();
	}
}
